package com.study.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: ChatNettyServerHandler
 * @Description:
 * @Date 2024/04/29 11:19
 * @Author songshaoqiu
 **/
public class ChatNettyServerHandler extends SimpleChannelInboundHandler<String> {

    private SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //存放Channel的容器，而且可以执行对每个channel进行操作的任务，任务由GlobalExeutor提供的单线程来执行的
    private static ChannelGroup channelGroup =new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 客户端连接上了服务端， 该方法会执行
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //获取到正在连接的客户端channel
        Channel channel = ctx.channel();
        String msg ="客户端-"+channel.remoteAddress()+"于"+ sdf.format(new Date())+"==>上线了"+"\n";
        System.out.println(msg);
        //获取到其他的客户端的channel 向其他客户端发送该客户端上线的消息。
        //DefaultChannelGroup 实际上也是一个channel 所以能直接调用writeAndFlush方法
        channelGroup.writeAndFlush(msg);
        //将当前连接的channel放到channelGroup中
        channelGroup.add(channel);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        //当前连接的channel
        Channel channel = channelHandlerContext.channel();
        //遍历所有channel
        channelGroup.forEach(ch->{
            //如果非 当前channel  广播
            if (ch!=channel){
                ch.writeAndFlush("客户端-"+channel.remoteAddress()+"说:"+s);
            }else{
                channel.writeAndFlush("我 说："+s);
            }
        });
    }

    /**
     * 客户端下线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String msg ="====>客户端-"+ctx.channel().remoteAddress()+"于"+ sdf.format(new Date())+"==>下线了"+"\n";
        System.out.println(msg);
        channelGroup.writeAndFlush(msg);
    }
}
